using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using WiimoteLib;
//using DeviceDiscovery;
using Franson.BlueTools;
using System.IO;

namespace WiiMoB
{
    public partial class Form1 : Form
    {
        Wiimote wm;

        // BlueTools Controls
        private System.Windows.Forms.MainMenu mainMenu;
        private System.Windows.Forms.Button discoverDevices;
        private System.Windows.Forms.ListBox deviceList;
        private System.Windows.Forms.Label networkLabel;
        private System.Windows.Forms.ListBox serviceList;
        private System.Windows.Forms.TextBox serviceOutput;

        private System.Windows.Forms.Button closeConnection;
        private System.Windows.Forms.Label deviceLabel;

        //private DiscoveryWindow m_discoveryWindow;

        private Manager manager = null;
        private Network m_network = null;

        private RemoteDevice m_currentDevice = null;
        private RemoteService m_currentService = null;
        private ServiceStream m_currentStream = null;

        private bool foundWiimote = false;
        private bool foundService = false;

        private byte[] m_buffer = new byte[25];	// Buffer to read data into


#region Accessors for form controls

        public System.Windows.Forms.Button DiscoverDevices
        {
            get { return discoverDevices; }
            set { discoverDevices = value; }
        }

        public System.Windows.Forms.ListBox DeviceList
        {
            get { return deviceList; }
            set { deviceList = value; }
        }

        public System.Windows.Forms.Label NetworkLabel
        {
            get { return networkLabel; }
            set { networkLabel = value; }
        }

        public System.Windows.Forms.ListBox ServiceList
        {
            get { return serviceList; }
            set { serviceList = value; }
        }

        public System.Windows.Forms.TextBox ServiceOutput
        {
            get { return serviceOutput; }
            set { serviceOutput = value; }
        }

        public System.Windows.Forms.Button CloseConnection
        {
            get { return closeConnection; }
            set { closeConnection = value; }
        }

        public System.Windows.Forms.Label DeviceLabel
        {
            get { return deviceLabel; }
            set { deviceLabel = value; }
        }

        #endregion Accessors for form controls


        public Form1()
        {
            InitializeComponent();

            //Should be good until 05/28 or so, then we can buy it ($100/$150 USD)
            //Or we can get another 14 day trial if we need to.
            Franson.BlueTools.License license = new Franson.BlueTools.License();
            license.LicenseKey = "HU5Uaeu162LOGX68oifhNlTRXvz0MRObHXEb";

            // Create a bluetooth manager and get the default radio device
            try
            {
                manager = Manager.GetManager();
                m_network = manager.Networks[0];
            }
            catch (Exception exc)
            {
                MessageBox.Show("GetManager/GetNetworks failed: " + exc.Message);
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            // Create an instance of Brian Peek's wiimote library. I have modified it
            // to contain an additional connect method, ConnectWithStream, that allows
            // you to pass in an already initialized stream that will work with the
            // library
            wm = new Wiimote();
        }

        // Run device discovery. If we find the wiimote, save it to a member variable
        private void buttonDeviceDiscovery_Click(object sender, EventArgs e)
        {
            labelDeviceDiscoveryStatus.Text = "Please wait. (up to 10 sec)";// Modified by justinb 05/20 to support ConnectWithStream (which does not pass a filestream)
            labelDeviceDiscoveryStatus.Update();

            try
            {
                // Start looking for devices on the network
                Device[] devices = m_network.DiscoverDevices();

                // After running device discovery, try to find a wiimote in the device list
                foreach (RemoteDevice thisDevice in devices)
                {
                    if (thisDevice.Name.StartsWith("Nintendo"))
                    {
                        labelDeviceDiscoveryStatus.Text = "WiiMote Found!";
                        m_currentDevice = thisDevice;

                        foundWiimote = true;
                        buttonServiceDiscovery.Enabled = true;
                    }
                }


                #region Commented Code - just trying different things
                // Here is code to access the wiimote directly assuming it is the only
                // other bluetooth device around.
                //RemoteDevice BTWiiMote = (RemoteDevice)devices[0];
                
                // The API will not allow this blank passkey (which is what the
                // wiimote expects) and 0/0000/" " does not work.
                //BTWiiMote.Bond("");

                // The Wii appears to have only one service, of class
                // "HumanInterfaceDeviceService"
                //RemoteService HIDService = BTWiiMote.Services[0];

                
                //foreach (RemoteDevice thisDevice in devices)
                //{
                    
                //    MessageBox.Show("Device: " + thisDevice);

                    // thisDevice.DiscoverServices(ServiceType.RFCOMM);
                    //BTWiiMote.DiscoverServices(ServiceType.HumanInterfaceDeviceService);
                    
                //    Service[] services = BTWiiMote.Services;
                //    foreach (Service thisService in services)
                //    {
                //        MessageBox.Show("Service: " + thisService.ToString());
                //    }
                ////}

                //currentService = BTWiiMote.ConnectService(0, "Nintendo RVL-CNT-01");
                //HIDService.SecurityPolicy = SecurityPolicy.None;
                //BTWiiMote.Bond("");
                
                //currentStream = HIDService.Stream;
                //MessageBox.Show(myStream.ToString());
                #endregion Commented Code - just trying different things

            }
            catch (BlueToolsException exc)
            {
                MessageBox.Show("Discover Devices failed: " + exc.Message);
                foundWiimote = false;
            }


            if (foundWiimote == false)
            {
                labelDeviceDiscoveryStatus.Text = "No Wiimote Found!";
                buttonServiceDiscovery.Enabled = false;
                buttonWiimoteConnect.Enabled = false;
                return;
            }

        
        }

        // Run service discovery. If we find on, add it to a member variable
        private void buttonServiceDiscovery_Click(object sender, EventArgs e)
        {
            if (m_currentDevice == null)
                return;

            
            try
            {
                // Attempt service discovery.. This is just a formality, as we know the
                // wiimote has only one service, a HID service.
                m_currentDevice.DiscoverServices(ServiceType.HumanInterfaceDeviceService);
                foreach (RemoteService thisService in m_currentDevice.Services)
                {
                    // Service name is same as device name, "Nintendo-RVL-CNT-01"
                    if (thisService.Name.StartsWith("Nintendo"))
                    {
                        labelServiceDiscoveryStatus.Text = "Found Wiimote HID Service";
                        m_currentService = thisService;
                        foundService = true;
                        buttonWiimoteConnect.Enabled = true;
                    }
                }
            }
            catch (BlueToolsException exc)
            {
                MessageBox.Show("Discover Services failed: " + exc.Message);
                foundService = false;
            }


            if (foundService == false)
            {
                labelServiceDiscoveryStatus.Text = "No HID Service found";
                buttonWiimoteConnect.Enabled = false;
            }
        }

        
        private void buttonWiimoteConnect_Click(object sender, EventArgs e)
        {
            if (m_currentService == null)
                return;

            labelWiimoteConnectStatus.Text = "Connecting to stream...";
            labelWiimoteConnectStatus.Update();
            

            // Getting error 10053 when trying to use a discovered service, so we are
            // substituting a hardcoded service here.
#if DEBUG
            m_currentDevice.ConnectService(0, "Nintendo RVL-CNT-01");
            m_currentService = (RemoteService)m_currentDevice.Services[0];
#endif


            // This is where it has been failing on me....
            m_currentStream = m_currentService.Stream;
            
            if (m_currentStream == null)
                return;

            MessageBox.Show("Got a stream, click OK to attempt connection");

            try
            {
                  wm.ConnectWithStream(m_currentStream);
            }
            catch (Exception ex)
            {
                MessageBox.Show(String.Format("Connection to wiimote failed. Exception: {0}", ex.Message.ToString()));
            }
        }

 


    }
}